package com.ylj.contact;

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.lzy.okgo.model.Response;
import com.ylj.contact.bean.ContactBean;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
    protected LoadingDialog mLoadingDialog = new LoadingDialog();
    ArrayList<ContactBean> mDataList = new ArrayList<>();
    TextView addTv ;
    TextView clearTv ;
    TextView addNoticeTv ;
    TextView clearNoticeTv ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addTv = findViewById(R.id.add_contact);
        clearTv = findViewById(R.id.clear_contact);
        addNoticeTv = findViewById(R.id.add_notice);
        clearNoticeTv = findViewById(R.id.clear_notice);

        addTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                XXPermissions.with(MainActivity.this).permission(Permission.WRITE_CONTACTS).request(new OnPermission() {
//                    @Override
//                    public void hasPermission(List<String> granted, boolean isAll) {
//                        addNoticeTv.setText("导入中");
//                        getData();
//                    }
//
//                    @Override
//                    public void noPermission(List<String> denied, boolean quick) {
//                        ToastUtils.show("需要联系人权限");
//                    }
//                });
                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                startActivity(intent);
                System.exit(0);
                finish();
            }
        });
        clearTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                XXPermissions.with(MainActivity.this).permission(Permission.WRITE_CONTACTS, Permission.READ_CONTACTS).request(new OnPermission() {
//                    @Override
//                    public void hasPermission(List<String> granted, boolean isAll) {
//                        clearNoticeTv.setText("删除中");
//                        mLoadingDialog.show(MainActivity.this, "正在删除");
//                        Observable.create(new ObservableOnSubscribe<String>() {
//                            @Override
//                            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
//                                int deleteNum = 200;
//                                List<String> mDataList = getContactsIds();
//                                if(mDataList.size()<=deleteNum){
//                                    batchDelContact(MainActivity.this, mDataList);
//                                }else{
//                                    for (int i=0;i<mDataList.size();i=(i+deleteNum)){
//                                        emitter.onNext("删除中，还剩"+(mDataList.size()-i)+"人");
//                                        List<String> mDeleteList = mDataList.subList(i, (i+deleteNum<mDataList.size())?(i+deleteNum):mDataList.size());
//                                        batchDelContact(MainActivity.this, mDeleteList);
//                                    }
//                                }
//                                emitter.onComplete();
//                            }
//                        }).subscribeOn(Schedulers.newThread())
//                                .observeOn(AndroidSchedulers.mainThread())
//                                .subscribe(new Observer<String>() {
//                                    @Override
//                                    public void onNext(String string) {
//                                        clearNoticeTv.setText(string);
//                                    }
//
//                                    @Override
//                                    public void onSubscribe(Disposable d) {
//
//                                    }
//
//                                    @Override
//                                    public void onComplete() {
//                                        mLoadingDialog.cancel();
//                                        clearNoticeTv.setText("删除成功");
//                                    }
//
//                                    @Override
//                                    public void onError(Throwable e) {
//                                        clearNoticeTv.setText("删除失败");
//                                        mLoadingDialog.cancel();
//                                    }
//                                });
//                    }
//
//                    @Override
//                    public void noPermission(List<String> denied, boolean quick) {
//                        ToastUtils.show("需要联系人权限");
//                    }
//                });
            }
        });
    }


    private void getData() {
        showLoadingDialog();
        Map<String,String> map = new HashMap();
        OkGoUtils.RequestOption requestOption = new OkGoUtils.RequestOption(MainActivity.this,
                "http://120.77.251.79/micxiaoxi/index.php/Home/Zfb/getuser",
//                "http://mic.fjjxhl.com/Jx/index.php/Home/Test/getuser",
                map,
                new AbsPostJsonStringCb(){
                    @Override
                    public void onSuccess(String str, String data) {
                        dismissLoadingDialog();
                        mDataList.clear();
                        Gson mGson = new Gson();
                        ArrayList<ContactBean> receList = mGson.fromJson(str, new TypeToken<List<ContactBean>>(){}.getType());
                        mDataList.addAll(receList);

                        mLoadingDialog.show(MainActivity.this, "正在导入联系人");
                        Observable.create(new ObservableOnSubscribe<String>() {
                            @Override
                            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                                int insertNum = 200;
                                int offset = 0;
                                if(mDataList.size()<=insertNum){
                                    insertContact(MainActivity.this, mDataList);
                                }else{
                                    for (int i = mDataList.size(); i>0; i = i-insertNum){
                                        emitter.onNext("导入中，剩余"+(mDataList.size()-offset)+"条");
                                        Log.e("ContactBean", i+"");
                                        List<ContactBean> mSubList = mDataList.subList(offset, (offset+insertNum<mDataList.size())?(offset+insertNum):mDataList.size());

                                        insertContact(MainActivity.this, mSubList);
                                        offset +=insertNum;
                                    }
                                }
                                emitter.onComplete();
                            }
                        }).subscribeOn(Schedulers.newThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Observer<String>() {
                                    @Override
                                    public void onNext(String string) {
                                        addNoticeTv.setText(string);
                                    }

                                    @Override
                                    public void onSubscribe(Disposable d) {

                                    }

                                    @Override
                                    public void onComplete() {
                                        mLoadingDialog.cancel();
                                        addTv.setText("点击重新导入");
                                        addNoticeTv.setText("导入完成");
                                        ToastUtils.show("导入完成");
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        addNoticeTv.setText("导入失败");
                                        mLoadingDialog.cancel();
                                    }
                                });
                    }

                    @Override
                    public void onError(Response<String> response) {
                        dismissLoadingDialog();
                        ToastUtils.show("出现异常");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });

        OkGoUtils.postJsonStringCallback(requestOption);
    }

    public void showLoadingDialog(){
        mLoadingDialog.show(this);
    }
    public void dismissLoadingDialog(){
        mLoadingDialog.cancel();
    }


     //插入本地联系人数据库
    public static int insertContact(Context context, List<ContactBean> list, boolean... action) throws OperationApplicationException, RemoteException {
        boolean isUpdate = false;
        if (action.length > 0) {
            if (action[0]) {
                isUpdate = action[0];
            }
        }
        if (list == null || list.size() < 0) {
            return 0;
        }
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        int rawContactInsertIndex = 0;
        int resutl = 0;
        for (ContactBean card : list) {
            rawContactInsertIndex = ops.size();
            if (isUpdate) {
                ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI)
                        .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                        .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                        .withYieldAllowed(true)
                        .build());
            } else {
                ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                        .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                        .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                        .withYieldAllowed(true)
                        .build());
            }
            //插入姓名
            if (!TextUtils.isEmpty(card.getName())) {
                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                        .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, card.getName())
                        .withYieldAllowed(true)
                        .build());
            }
            //插入电话
            if (!TextUtils.isEmpty(card.getTel())) {
                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                        .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
                        .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, card.getTel())
                        .withYieldAllowed(true)
                        .build());
            }

        }
        // 真正添加
            ContentProviderResult[] results = context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
//            if (results != null && results.length > 0) {
//                for (ContentProviderResult result : results) {
//                    SoutUtils.out("URI:" + result.uri, "count:" + result.count);
//                }
//                resutl++;
//            }
            resutl = results.length;
        return resutl;
    }




    /**
     * 获得所有联系人的id
     * @return List<String>
     */
    public List<String> getContactsIds(){

        List<String> ids = new ArrayList<String>();

        Uri uri = ContactsContract.Contacts.CONTENT_URI;

        Cursor cursor = getContentResolver().query(uri, new String[]{ ContactsContract.Contacts._ID }, null, null, null);
        while (cursor.moveToNext()) {
            ids.add(cursor.getString(0));
        }
        cursor.close();

        return ids;
    }

    public static void batchDelContact(Context context, List<String> list) {
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
//            ContactBean model = list.get(i);
//            ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, Long.parseLong(list.get(i))))
//                    .withYieldAllowed(true)
//                    .build());
//            ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, Long.parseLong(list.get(i))))
//                    .withYieldAllowed(true)
//                    .build());
            //delete contact
            ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
                    .withSelection(ContactsContract.RawContacts.CONTACT_ID+"="+list.get(i), null)
                    .withYieldAllowed(true)
                    .build());
            //delete contact information such as phone number,email
            ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                    .withSelection(ContactsContract.Contacts.Data.RAW_CONTACT_ID + "=" + list.get(i), null)
                    .withYieldAllowed(true)
                    .build());
        }
        try {
            context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (OperationApplicationException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
